<template>
  <div class="xpanel-wrapper-100">
    <div class="xpanel-wrapper-100">
<!--      <el-input placeholder="请输入关键字过滤" v-model="filterText"></el-input>-->
      <div class="catalog-tree" v-show="layerVisable">
        <el-tree
            :default-expanded-keys="expandNode"
            :data="config.catalogTreeData"
            :props="defaultProps"
            show-checkbox
            node-key="nid"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            @check-change="catalogItemClick">
    <span class="custom-tree-node" slot-scope="{node,data}">
      <span>{{ data.label }}</span>
      <span class="item-btns"
            v-if="data.type===1"
            v-show="data.visible">
        <i class="resource-catalog"
           v-for="(btn,btnindex) in data.btns"
           :key="btnindex" :class="btn.classname"
           :type="btn.type"
           :title="btn.title"
           @click="operateItem(data,btn)"></i>
      </span>
    </span>
        </el-tree>
      </div>
      <!--CatalogItem class="catalog" :list="config.catalogTreeData"></CatalogItem-->
    </div>
    <div id="layerTransPopup-plan" class="layerTransPopup" v-show="opacityConfig.transPopup===true">
      <div class="layerTransPopupTit">
        <label title="图层透明度" style="color:#ffffff;">图层透明度：{{ opacityConfig.LayerName }}</label>
        <i class="win-close el-icon-close" title="关闭" @click="closeOpacity()"></i>
      </div>
      <el-slider class="sliderOpacty" v-model="opacityConfig.value" :marks="opacityConfig.marks"></el-slider>
    </div>
  </div>
</template>

<script>
import globalmf from "@/utils/Global/GlobalMapFunction";
import * as globalcf from "@/utils/Global/GlobalCommonFunction";
import {extend} from "@/utils/Global/GlobalCommonFunction";
// import CatalogItem from "@/components/mapPortal/layerManager/CatalogItem";
import Bus from "@/utils/bus";
import {
  deleteFavoriteLayer,
  deleteTempLayer,
  getCatalogQueryConfigListById,
  getFavoriteLayerList,
  getResourceCatalogList,
  getTempLayerList,
  getTempLayerTempConfig,
  insertFavoriteLayer,
  insertTempLayer
} from "@/api/portal/catalog";

export default {
  name: "Catalog",
  components: {
    // CatalogItem
  },
  data() {
    return {
      expandNode: ["temp"],//why20220401 设置默认展开临时图层 加载shp功能只有展开才可以  不然有问题 点击前不能加进去节点
      attribute: {
        "dataurl": null,
        "totalCount": 0,
        "fromIndex": 0,
        "toIndex": 19
      },
      //图层目录配置信息
      config: {
        "newAddFavoriteDataItem": {},
        "tempLayerType": 999,
        "checkedNodes": [],
        "catalogData": [],
        tempNode: {
          "label": "临时图层",
          "type": 0,
          "children": [{
            "label": "临时矢量",
            "type": 0,
            "children": []
          }, {
            "label": "临时影像",
            "type": 0,
            "children": []
          }]
        },
        "catalogTreeData": [{
          "label": "临时图层",
          "nid": "temp",
          "id": 'temp',
          "type": 0,
          "visableCata": false,
          "itemClick": false,
          "level": 1,
          "enflag": "catalogImage/catalogIcon/lstc.png",
          "explain": "存放导入的临时图层",
          "children": [{
            "label": "临时矢量",
            "type": 0,
            "level": 2,
            "visableCata": false,
            "itemClick": false,
            "children": []
          }, {
            "label": "临时影像",
            "type": 0,
            "children": []
          }]
        }, {
          "label": "我的收藏夹",
          "type": 0,
          "level": 1,
          "children": [],
          "id": 'myfavourite',
          "visableCata": false,
          "itemClick": false,
          "enflag": "catalogImage/catalogIcon/wdscj.png",
          "explain": "存放所有收藏的图层"
        }],
      },
      //图层信息默认配置项
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      detailLayers: [],
      filterText: "",
      enum: {
        nodeType: {"normal": "n", "favorite": "f", "temp": "t"}
      },
      //图层操作按钮
      itemBtns: {
        "normal": [
          {"classname": "el-icon-location", "type": "locate", "title": "定位"},
          {"classname": "el-icon-pie-chart", "type": "opacity", "title": "透明度"},
          // {"classname": "el-icon-tickets", "type": "open-attr", "title": "属性表"},
          {"classname": "el-icon-picture-outline", "type": "legend", "title": "图例"},
          {"classname": "el-icon-star-off", "type": "favorite", "title": "收藏"}
        ],
        "favorite": [
          {"classname": "el-icon-location", "type": "locate", "title": "定位"},
          {"classname": "el-icon-pie-chart", "type": "opacity", "title": "透明度"},
          // {"classname": "el-icon-tickets", "type": "open-attr", "title": "属性表"},
          {"classname": "el-icon-picture-outline", "type": "legend", "title": "图例"},
          {"classname": "el-icon-star-on", "type": "favorite", "title": "收藏"}
        ],
        "temp": [
          {"classname": "el-icon-document", "type": "save", "title": "保存"},
          {"classname": "el-icon-delete", "type": "delete", "title": "删除"}
        ],
      },
      legend: "",
      opacityConfig: {
        LayerName: '', //被调节的图层透明度名称
        marks: {
          0: {style: {color: '#1989FA'}, label: this.$createElement('span', '0')},
          25: {style: {color: '#1989FA'}, label: this.$createElement('span', '25')},
          50: {style: {color: '#1989FA'}, label: this.$createElement('span', '50')},
          75: {style: {color: '#1989FA'}, label: this.$createElement('span', '75')},
          100: {style: {color: '#1989FA'}, label: this.$createElement('span', '100')}
        },
        operateLayer: null, //操作图层 透明度
        transPopup: false,//图层透明度显示与否
        value: 0,//调节透明度的值
      },
      openIds: [],
      tree: null,
      zIndex: 100,
    }
  },
  props: {
    layerVisable: {//加载进来的图层是否可见
      type: Boolean,
      default() {
        return true
      }
    },
    queryFieldNameXZQ: {
      type: String,
      default() {
        return 'f_xzqqsdm'
      }
    },
    map: {
      type: Object,
      default() {
        return {}
      }
    },
    mapRegion: {
      type: Object,
      default() {
        return {
          f_levels: 1,
          f_regioncode: "f_regioncode",
          f_userid: 1,
          f_username: "f_username",
          f_name: "",
          prjcode: "EPSG:4490",
          userPrjCode: "EPSG:4490",
          f_xmax: 140,
          f_xmin: 110,
          f_ymax: 53,
          f_ymin: 42,
          geomwkt: "",
        }
      }
    }
  },
  mounted() {
    let that = this;
    that.Init();
    //2022年4月2日 LQ
    Bus.$on('getNodeDataInLeftCatalog', params => {
      let nodeG = {id: 0, children: that.config.catalogTreeData};
      // let node = that.getNodeDataByID(that.config.catalogTreeData[2], params.id);
      let node = that.getNodeDataByID(nodeG, params.id);
      if (node) {
        that.catalogItemClick(node, params.open);
      }
    });
    Bus.$on('getOperateItemInLeftCatalog', params => {
      that.operateItem(params.item, params.btn);
    });
    //why20220331
    Bus.$on('updateAttrTablePage', msg => {
      //读出属性表第一页数据
      that.attribute.dataurl = that.operateLayer.dataUrl + "/datasources/" + that.operateLayer.datasourceName + "/datasets/" + that.operateLayer.datasetName + "/features.rjson?hasGeometry=true";
      //sql查询
      let from = 20 * msg[0] - 20;
      let to = 20 * msg[0] - 1;
      let prj = msg[3];
      that.queryFeaturesByRegionsAxios(that, prj,
          {
            fromIndex: from,
            toIndex: to
          });
    });
    Bus.$on('updateTempLayer', param => {
      that.updateTempLayer(param);
    });
  },
  beforeDestroy() {
    Bus.$off('getNodeDataInLeftCatalog');
    Bus.$off('getOperateItemInLeftCatalog');
    //why20220331
    Bus.$off('updateAttrTablePage');
    Bus.$off('updateTempLayer');
  },
  methods: {
    Init() {
      this.queryFavoriteLayerAxios({operatetype: "query"});
      this.queryTempLayerAxios({operatetype: "query"});
      this.queryCatalogAxios();
    },
    /**
     * 目录节点勾选点击事件 zpf 2022年3月29日
     * @param data
     * @param isCheck
     * @param checkNode
     */
    catalogItemClick(data, isCheck, checkNode) {
      let that = this;
      data.visible = isCheck;
      if (data.nodeType == that.enum.nodeType.normal || data.nodeType == that.enum.nodeType.favorite) {
        let isFavorite = false;
        for (let i in that.config.catalogTreeData[1].children) {
          let node = that.config.catalogTreeData[1].children[i];
          if (node.id == data.id) {
            node.visible = isCheck;
            isFavorite = true;
          }
        }
        if (data.nodeType == that.enum.nodeType.normal && isFavorite) {
          for (let i = 0; i < data.btns.length; i++) {
            if (data.btns[i].type === "favorite") {
              data.btns[i].classname = "el-icon-star-on";
            }
          }

        }
        let nodeTypeBe = data.nodeType == that.enum.nodeType.normal ? that.enum.nodeType.favorite : that.enum.nodeType.normal;
        this.$refs.tree.setChecked(nodeTypeBe + "-" + data.id, isCheck, false);
      }
      try {
        that.setNodeVisible(data, isCheck, null);
      } catch (e) {

      }
    },
    /**
     * 关闭透明度窗口
     * @constructor
     */
    closeOpacity: function () {
      let that = this;
      that.opacityConfig.transPopup = false;
      //why20211201所有图层透明度都关闭
      that.map.getLayers().forEach(function (layer, i) {
        if (layer.getVisible()) {
          layer.setOpacity(1);
        }
      });
    },
    /**
     * 过滤节点 zpf 2022年3月29日
     * @param value
     * @param data
     * @returns {boolean}
     */
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /**
     * 格式化目录树数据
     * @param parentNodes
     * @param parentId
     * @param checkedid
     * @param catalogData
     * @constructor
     */
    formatParentNodesTreeData(parentNodes, parentId, checkedid, catalogData) {
      let that = this;
      for (let i in catalogData) {
        let nodeItem = catalogData[i];
        if (parentId === "") {
          let aaa = 1;
        }
        //2022年3月21日 LQ 数据库里根目录有的为null，有的为''
        if (nodeItem.pid == parentId || (nodeItem.pid == null && parentId == '')) {
          let name = nodeItem.name;
          let node = that.getLayerItemData(nodeItem, false, that.enum.nodeType.normal, that.itemBtns.normal);
          if (node.id == checkedid) {
            node.checked = true;
          }
          if (node.name === "影像") {
            let aaa = 1;
          }
          that.formatParentNodesTreeData(node.children, node.id, "", catalogData);

          parentNodes.push(node);
        }
      }
    },
    /**
     * 获取目录节点layerItem数据对象
     * @param layerItem {} 节点数据
     * @param visible bool 是否可见
     * @param nodeType string 节点类型
     * @param btns [] 按钮列表
     * @returns {*}
     */
    getLayerItemData(layerItem, visible, nodeType, btns) {
      return globalcf.extend({}, {
        "label": layerItem.name,
        "name": layerItem.name,
        "nid": nodeType + "-" + layerItem.id,
        "visible": visible,
        "nodeType": nodeType,
        "btns": JSON.parse(JSON.stringify(btns)),
        "children": []
      }, layerItem);
    },
    getNodeDataByID(alldata, id) {
      if (alldata.id == id) {
        return alldata;
      } else {
        if (alldata.children != null) {
          for (let i = 0; i < alldata.children.length; i++) {
            var flag = this.getNodeDataByID(alldata.children[i], id);
            if (flag) {
              return flag;
            }
          }
        }
      }
      return null;
    },
    /**
     * 加载地图服务
     * @param data
     * @param checked
     * @param type
     * @constructor
     */
    loadMapService(data, checked, type) {
      let that = this;
      let layer = globalmf.getLayerById(that.map, data.id);
      if (checked) {//选中状态
        if (layer) {//图层已存在
          layer.setVisible(that.layerVisable)
          // if (!layer.getVisible()) {
          //   layer.setVisible(true);
          // }
        } else {
          that.map.getLayers().forEach(function (layer, i) {
            if (layer.get("type") == type) {
              that.zIndex++;
            }
          });
          var Layer;
          var feature = null;
          //根据geom获取geometry
          if (that.mapRegion.f_levels != 1) {
            var geomwkt = that.mapRegion.geomwkt;
            var format = new ol.format.WKT();
            feature = format.readFeature(geomwkt,
                {
                  dataProjection: that.mapRegion.prjcode,
                  featureProjection: that.map.getView().getProjection().getCode()
                });
          }

          var sys = 'EPSG:4490';
          if (data.sys != "" && data.sys != null) {
            sys = 'EPSG:' + data.sys;
          }
          var option = {
            url: data.url,
            name: data.name,
            id: data.id,
            sys: sys,
            zIndex: that.zIndex,
            type: type,
            zmin: data.zmin,
            zmax: data.zmax,
            servicetype: data.f_servicetype,
            visible: that.layerVisable
          };
          if (data.f_servicetype == 1) {// 加载 rest
            Layer = globalmf.addREST4490Layer(that.map, option, feature);
          } else if (data.f_servicetype == 4) {//加载 wmts
            Layer = globalmf.addWMTS4490Layer(that.map, option, feature);
          } else if (data.f_servicetype == 7) {//加载 wmts
            Layer = globalmf.addTDTWMTSService(that.map, option, feature);
          } else {
            globalmf.addServiceToMap(that.map, option, feature);
          }
        }
      } else {
        //2022年7月18日 LQ 设置不显示，不给移除了
        //  globalmf.clearLayerById(that.map, data.id);
        globalmf.clearLayerById(that.map, data.id);

      }
      //why20211013更新卷帘和分析选择图层
      //2022年3月22日 LQ 先注释掉，需要的时候加上
      // that.mapCore.UpDateSelectLayers();
    },
    //why20211019 打开图例
    openLegendById: function (id, catalogData) {
      let that = this;
      for (var i in catalogData) {
        let nodeItem = catalogData[i];
        if (nodeItem.id == id) {
          let title = nodeItem.name;
          if (nodeItem.type == 1) {
            if (nodeItem['legend'] != "") {
              that.legend = nodeItem['legend'];
              this.$emit('ShowLegend', that.legend);
            } else {
              that.$message({
                message: '此图层无图例',
                type: 'warning'
              });
            }
            break;
          }
        }
        that.openLegendById(id, nodeItem.children);
      }
    },
    /**
     * 图层节点按钮操作 zpf 2022年3月29日
     * @param data
     * @param btn
     */
    operateItem(data, btn) {
      let that = this;
      let layerId = data.id;
      if (data.type === 0) {
        return;
      }
      let param = {};
      switch (btn.type) {
        case "locate"://定位
          that.setLocationLayerById(layerId);
          break;
        case "opacity"://设置图层透明度
          that.setOpacityLayerById(layerId);
          break;
        case "open-attr"://打开图层属性表
          that.openLayerAttrById(layerId);
          break;
        case "legend"://打开图层图例
          that.openLegendById(layerId, that.config.catalogTreeData);
          break;
        case "favorite"://收藏图层
          param = {
            layerid: layerId,
            operatetype: "add"
          };
          let layerItem = globalmf.getLayerById(that.map, layerId);
          if (btn.classname == "el-icon-star-off") {
            btn.classname = "el-icon-star-on";
            btn.title = "取消收藏";
          } else {
            btn.classname = "el-icon-star-off";
            btn.title = "收藏";
            param.operatetype = "delete";
          }
          that.updateFavoriteLayerItem(param);
          break;
        case "save"://保存临时图层
          let tempLayer = globalmf.getLayerById(that.map, layerId);
          if (tempLayer) {
            let features = tempLayer.getSource().getFeatures;
            let geojsonFormat = new ol.format.GeoJSON();
            let featuresGeojson = geojsonFormat.writeFeatures(features);
            param = {
              "id": layerId,
              "geojson": featuresGeojson,
              "operatetype": "add",
              "name": layerName
            };
            that.updateTempLayer(param);
          }
          break;
        case "delete"://删除临时图层
          param = {
            "id": layerId,
            "operatetype": "delete",
            "name": layerName
          };
          that.updateTempLayer(param);
          break;
      }
    },
    /**
     * 初始化目录树数据  zpf 2022年3月26日
     * @param param
     * @returns {{getAllResponseHeaders: function(): *|null, abort: function(*=): this, setRequestHeader: function(*=, *): this, readyState: number, getResponseHeader: function(*): null|*, overrideMimeType: function(*): this, statusCode: function(*=): this}|*|jQuery}
     * @constructor
     */
    queryCatalogAxios(param) {
      let that = this;
      getResourceCatalogList().then(res => {
        let json = res.data;
        that.config.catalogData = json.catalogData;
        that.formatParentNodesTreeData(that.config.catalogTreeData, "", "", that.config.catalogData);
      }).catch(res => {
        console.log('queryCatalogAxios', res);
      });
    },
    /**
     * 查询收藏夹图层
     * @param param
     * @returns {{getAllResponseHeaders: function(): *|null, abort: function(*=): this, setRequestHeader: function(*=, *): this, readyState: number, getResponseHeader: function(*): null|*, overrideMimeType: function(*): this, statusCode: function(*=): this}|*|jQuery}
     * @constructor
     */
    queryFavoriteLayerAxios(param) {
      let that = this;
      getFavoriteLayerList().then(res => {
        let json = res.data;
        if (json.layerIds && json.layerIds.length > 0) {
          for (let i in json.layerIds) {
            let layerItem = json.layerIds[i];
            let newLayerItem = that.getLayerItemData(layerItem, false, that.enum.nodeType.favorite, that.itemBtns.favorite)
            that.config.catalogTreeData[1].children.push(newLayerItem);

          }
        }
      }).catch(res => {
        console.log('queryFavoriteLayerAxios', res);
      });
    },
    queryTempLayerAxios(param) {
      let that = this;
      getTempLayerList().then(res => {
        let json = res.data;
        if (json.layerIds && json.layerIds.length > 0) {
          that.tempLayerIds = [];
          for (let i in json.layerIds) {
            let layerItem = json.layerIds[i];
            let newLayerItem = that.getLayerItemData(layerItem, false, that.enum.nodeType.temp, that.itemBtns.temp)
            that.config.catalogTreeData[0].children[0].children.push(newLayerItem);
          }
        }
      }).catch(res => {
        console.log('queryTempLayerAxios', res);
      });
    },
    //why20211004 定位至图层
    setLocationLayerById(id) {
      let that = this;
      let layerId = id;
      let locateLayer = globalmf.getLayerById(that.map, layerId);
      let extent = [110, 42, 140, 53]; //= [110, 42, 140, 53]
      if (locateLayer.getExtent()) {
        extent = locateLayer.getExtent();
      } else if (locateLayer.getSource() instanceof ol.source.WMTS) {
        extent = locateLayer.getSource().tileGrid.extent_;
        let defaultPrjCode = that.mapRegion.prjcode;
        let mapPrjCode = that.map.getView().getProjection().getCode();
        if (defaultPrjCode != mapPrjCode) {
          let extend1 = ol.proj.transform([extent[0], extent[1]], defaultPrjCode, mapPrjCode);
          let extend2 = ol.proj.transform([extent[2], extent[3]], defaultPrjCode, mapPrjCode);
          extent = [extend1[0], extend1[1], extend2[0], extend2[1]];
        }
      } else if (locateLayer.getSource() instanceof ol.source.Vector) {
        extent = locateLayer.getSource().getExtent();
      }
      globalmf.zoomToExtent(that.map, extent);
    },
    /**
     * 设置节点是否可见 zpf 2022年3月29日
     * @param data
     * @param checked
     * @param elem
     * @constructor
     */
    setNodeVisible(data, checked, elem) {
      let that = this;
      if (data.type == 0) {//获取下面所有子节点. 0表示目录
        let children = data.children;
        if (children.length > 0) {
          for (let i in children) {
            let nodeItem = children[i];
            that.setNodeVisible(nodeItem, checked);
          }
        }
      } else if (data.type == 1) {//1表示图层
        that.loadMapService(data, checked, 1);
        //why20211101
        that.openIds.push(data.id);
      } else if (data.type == 2) {//不知道2是什么，可能是导入的临时图层。
        let layer = globalmf.getLayerById(that.map, data.id);
        if (layer) {
          if (checked) {
            layer.setVisible(true);
          } else {
            layer.setVisible(false);
          }
        }
      } else if (data.type == that.config.tempLayerType) {//why20220401
        var layer = globalmf.getLayerById(that.map, data.id);
        if (layer) {
          if (checked) {
            layer.setVisible(true);
          } else {
            layer.setVisible(false);
          }
        } else {
          var geojson = data.geojson;
          var geojsonObj = null;
          eval('geojsonObj=' + geojson + ';');
          var geojsonFormat = new ol.format.GeoJSON();
          var features = geojsonFormat.readFeatures(geojsonObj);
          var tempLayer = globalmf.createLayer(that.map, features, data.name, data.id, that.config.tempLayerType, 'rgba(153,234,243,0.5)', '#38c1ea');
          globalmf.zoomToLayer(that.map, tempLayer);
        }
      }
      if (data.type != 0) {//联动设置收藏夹图层是否可见

      }
    },
    //why20210928 透明度
    setOpacityLayerById(id) {
      let that = this;
      that.opacityConfig.transPopup = true;//显示
      let layerId = id;
      that.opacityConfig.operateLayer = globalmf.getLayerById(that.map, layerId);
      //why20211201 设置当前透明度
      let opacity = 1 - that.opacityConfig.operateLayer.getOpacity();
      that.opacityConfig.Value = opacity * 100;
      that.opacityConfig.LayerName = that.opacityConfig.operateLayer.getProperties().name;
    },
    //why20220331 打开属性表
    openLayerAttrById(id) {
      var that = this;
      var layerId = id;
      var attrLayer = globalmf.getLayerById(that.map, layerId);
      var prj = attrLayer.getSource().getProjection().getCode();
      var queryLayers = that.detailLayers.find((item, index) => {
        return item.id == layerId;
      });
      if (queryLayers && queryLayers.length > 0) {
        that.operateLayer = queryLayers[0];
        that.openLayerAttrTable(prj);
      } else {
        getCatalogQueryConfigListById(layerId).then((res) => {
          if (res.data.queryData.length > 0) {
            var obj = res.data.queryData[0];
            var name = obj.f_name;
            var dataUrl = obj.f_url; //数据服务地址
            var analysisUrl = obj.f_analysisurl; //分析服务地址
            var datasourceNames = [{"name": obj.f_datasource, "value": obj.f_datasource}];
            var datasetNames = [{"name": obj.f_dataset, "value": obj.f_dataset}];
            var fieldData = JSON.parse(obj.f_fieldconfig);
            if (analysisUrl != null && analysisUrl != "") {
              var layerjson = {
                "name": name,
                "id": id,
                "dataUrl": dataUrl,
                "analysisUrl": analysisUrl,
                "datasourceName": datasourceNames[0].name,
                "datasetName": datasetNames[0].name,
                "fieldData": fieldData
              };
              that.detailLayers.push(layerjson);
              that.operateLayer = layerjson;
            }
          }
          that.openLayerAttrTable(prj);
        });
      }
    },
    //why20220331
    openLayerAttrTable: function (prj) {
      //打开属性表
      var that = this;
      if (that.operateLayer && that.operateLayer != "") {
        //读出属性表第一页数据
        that.attribute.dataurl = that.operateLayer.dataUrl + "/datasources/" + that.operateLayer.datasourceName + "/datasets/" + that.operateLayer.datasetName + "/features.rjson?hasGeometry=true";
        //sql查询
        that.queryFeaturesByRegionsAxios(that, prj,
            {
              fromIndex: 0,
              toIndex: that.attribute.toIndex
            });
      } else {
        that.$message({
          message: '本图层不支持查看属性表',
          type: 'warning'
        });
      }
    },
    //why20220331
    queryFeaturesByRegionsAxios: function (obj, prj, param) {
      //sql查询
      var that = obj;
      that.attribute.features = [];
      that.attribute.fromIndex = param.fromIndex;
      that.attribute.toIndex = param.toIndex;
      var attributeFilter = null;
      if (that.mapRegion.f_levels != 1) {
        attributeFilter = that.queryFieldNameXZQ + " LIKE '" + that.mapRegion.f_regioncode + "%'";
      }
      var sqlParam = new SuperMap.GetFeaturesBySQLParameters({
        queryParameter: {
          name: that.operateLayer.datasetName + "&" + that.operateLayer.datasourceName,
          attributeFilter: attributeFilter
        },
        datasetNames: [that.operateLayer.datasourceName + ":" + that.operateLayer.datasetName],
        fromIndex: that.attribute.fromIndex, //分页查询参数用来返回查询结果的数量 定义查询结果的最小索引号
        toIndex: that.attribute.toIndex, //分页查询参数用来返回查询结果的数量 定义查询结果的最大索引号
      });
      new ol.supermap.FeatureService(that.operateLayer.dataUrl).getFeaturesBySQL(sqlParam, function (serviceResult) {
        that.attribute.totalCount = serviceResult.result.totalCount;
        var features = (new ol.format.GeoJSON()).readFeatures(serviceResult.result.features);
        if (features.length > 0) {
          //why20211018转换投影
          var defaultPrjCode = that.mapRegion.prjcode;
          var mapPrjCode = that.map.getView().getProjection().getCode();
          if (defaultPrjCode != mapPrjCode) {
            for (var i = 0; i < features.length; i++) {
              features[i].getGeometry().transform(that.mapRegion.prjcode, that.map.getView().getProjection().getCode());
            }
          }
          //结果显示在属性表里面
          var params = [features, that.operateLayer.fieldData, that.map, that.operateLayer.id,
            that.attribute.totalCount, that.attribute.fromIndex, that.attribute.toIndex, prj, false];
          Bus.$emit('setMapBottom', "300px");
          Bus.$emit('intCatalogAttributeTable', params);

        }
      });
    },
    /**
     * 设置目录树图层的收藏夹不可见
     * @param treeData
     * @param id
     * @constructor
     */
    setCatalogTreeDataFavoriteBtn(treeData, id) {
      let that = this;
      for (let i in treeData) {
        let treeNode = treeData[i];
        if (treeNode.id == id && treeNode.btns) {
          for (let i = 0; i < data.btns.length; i++) {
            if (data.btns[i].type === "favorite") {
              data.btns[i].classname = "el-icon-star-off";
            }
          }
        } else {
          that.setCatalogTreeDataFavoriteBtn(treeNode.children, id);
        }
      }
    },
    /**
     * 更新收藏图层
     * @param layerItem
     * @param operateType
     * @constructor
     */
    updateFavoriteLayerItem(param) {
      let that = this;
      switch (param.operatetype) {
        case "add":
          insertFavoriteLayer({
            "layerId": param.layerid
          }).then(res => {
            let json = res.data;
            let layerItems = json.layerIds;
            for (let i in layerItems) {
              let layerItem = json.layerIds[i];
              let newLayerItem = that.getLayerItemData(layerItem, true, that.enum.nodeType.favorite, that.itemBtns.favorite);
              that.config.catalogTreeData[1].children.push(newLayerItem);
              that.config.newAddFavoriteDataItem = newLayerItem;
              that.$nextTick(function () {
                that.$refs.tree.setChecked(that.enum.nodeType.favorite + "-" + that.config.newAddFavoriteDataItem.id, true, false);
              });
            }
          }).catch(res => {
            console.log('insertFavoriteLayer', res);
          });
          break;
        case "delete":
          deleteFavoriteLayer(param.layerid).then(res => {
            let json = res.data;
            let layerItems = json.layerIds;
            for (let i in layerItems) {
              let layerItem = json.layerIds[i];
              let favoriteNote = that.config.catalogTreeData[1].children;
              for (let j in favoriteNote) {
                let nodeItem = favoriteNote[j];
                if (nodeItem.id == layerItem.id) {
                  that.config.catalogTreeData[1].children.splice(j, 1);
                }
              }
              that.setCatalogTreeDataFavoriteBtn(that.config.catalogTreeData, layerItem.id);
            }
          }).catch(res => {
            console.log('deleteFavoriteLayer', res);
          });
          break;
      }
    },
    //why20220401
    updateTempLayer(param) {
      let that = this;
      param.type = that.config.tempLayerType;
      switch (param.operatetype) {
        case "temp":
          getTempLayerTempConfig(param).then(res => {
            let vectorTempLayers = that.config.catalogTreeData[0].children[0].children;
            for (let i in res.data.updateData.tempLayers) {
              let tempLayerItem = res.data.updateData.tempLayers[i];
              tempLayerItem.type = parseInt(tempLayerItem.type)
              let newLayerItem = that.getLayerItemData(tempLayerItem, true, that.enum.nodeType.temp, that.itemBtns.temp);
              vectorTempLayers.push(newLayerItem);
              let geojson = tempLayerItem.geojson;
              let geojsonObj = JSON.parse(geojson);
              let geojsonFormat = new ol.format.GeoJSON();
              let features = geojsonFormat.readFeatures(geojsonObj);
              let tempLayer = globalmf.createLayer(that.map, features, tempLayerItem.name, tempLayerItem.id,
                  that.config.tempLayerType, 'rgba(100,100,100,0.2)', '#005aff');

              globalmf.zoomToLayer(that.map, tempLayer);

              //去CatalogConsult里处理添加的temp图层
              that.$nextTick(function () {
                let ccparam = extend({},newLayerItem,{
                  "operatetype":"temp",
                });
                Bus.$emit("updateTempLayer_CatalogConsult", ccparam)
                that.$refs.tree.setChecked(that.enum.nodeType.temp + "-" + tempLayerItem.id, true, false);
                // that.map.addLayer(tempLayer);
              });
            }
          }).catch(res => {
            console.log('getTempLayerTempConfig', res);
          });
          break;
        case "add":
          insertTempLayer(param).then(res => {
            let vectorTempLayers = that.config.catalogTreeData[0].children[0].children;
            for (let i in res.data.updateData.tempLayers) {
              let tempLayerItem = res.data.updateData.tempLayers[i];
              for (let j in vectorTempLayers) {
                if (vectorTempLayers[j].id == tempLayerItem.id) {
                  vectorTempLayers[j].btns[0].classname = "el-icon-s-claim";
                  vectorTempLayers[j].btns[0].type = "saved";
                  vectorTempLayers[j].btns[0].title = "已保存";
                }
              }
              let ccparam = extend({},tempLayerItem,{
                "operatetype":"add",
              });
              Bus.$emit("updateTempLayer_CatalogConsult", ccparam)
            }
          }).catch(res => {
            console.log('insertTempLayer', res);
          });
          break;
        case "delete":
          deleteTempLayer(param).then(res => {
            let vectorTempLayers = that.config.catalogTreeData[0].children[0].children;
            if (res.data.updateData.tempLayers.length > 0) {
              for (let i in res.data.updateData.tempLayers) {
                let tempLayerItem = res.data.updateData.tempLayers[i];
                for (let j in vectorTempLayers) {
                  if (vectorTempLayers[j].id == tempLayerItem.id) {
                    vectorTempLayers.splice(j, 1);
                  }
                }
                let ccparam = extend({},tempLayerItem,{
                  "operatetype":"delete",
                });
                Bus.$emit("updateTempLayer_CatalogConsult", ccparam)
              }
            }
          }).catch(res => {
            console.log('deleteTempLayer', res);
          });
          break;
      }
    }
  },
  watch: {
    'filterText'(val) {
      this.$refs.tree.filter(val);
    },
    'opacityConfig.value'(nValue, oValue) {//图层透明度调节中
      let opacity = 1 - nValue / 100;
      this.opacityConfig.operateLayer.setOpacity(opacity);
    },
  }
}
</script>

<style scoped>
.resource-catalog {
  margin-left: 5px;
}

.xpanel-wrapper-100 {
  height: 100%;
}

::v-deep .catalog-tree {
  z-index: 0;
  height: 100%;
  margin: -40px 0px 0px 0px;
  padding: 50px 0px 0px 0px;
}

::v-deep .el-tree {
  background: transparent;
  color: #fff;
  height: 100%;
  overflow: auto;
}

::v-deep .el-input__inner {
  background-color: transparent;
  color: #fff;
}

::v-deep .el-input__inner:focus {
  border-color: #fbffff;
}

::v-deep .el-tree-node__content:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

::v-deep .el-tree-node:focus > .el-tree-node__content {
  background-color: #008680;
}

.item-btns {
  /*width: 100%;*/
}

::v-deep .el-scrollbar__wrap {
  overflow-x: hidden;
  overflow-y: auto;
  height: 100%;
}

.sliderOpacty {
  margin: 0 5px 5px 5px;
  padding: 0 10px 5px 5px;
}

::v-deep .el-slider__button {
  border: 2px solid #008680;
  background-color: #004643;
}

::v-deep .el-slider__stop {
  background-color: #008680;
}

::v-deep .el-slider__bar {
  background-color: #008680;
}

::v-deep .el-slider__marks-text {
  color: #008680 !important;
  font-size: 12px;
}

/* 图层透明度控制框 */
.layerTransPopup {
  left: 368px;
  top: 75px;
  cursor: pointer;
  position: fixed;
  width: 315px;
  z-index: 8999;
  font-size: 12px;
  background: #fff;
  border: 1px solid #008680;
  box-shadow: 0 0 3px #555;
  -moz-box-shadow: 0 0 3px #555;
  -webkit-box-shadow: 0 0 3px #555;
  /*behavior: url(../css/PIE.htc);*/
}

.layerTransPopupTit {
  width: 100%;
  height: 30px;
  line-height: 30px;
  background: #008680;
  border-bottom: 1px solid #ccc;
  padding: 0 6px;
}

.layerTransPopupTit span {
  padding: 4px 6px;
  font-size: 12px;
  color: #fff;
}

.layerTransRangeContent {
  width: 305px;
  height: 45px;
  padding: 5px 10px 0 10px;
  text-align: center;
}

.win-close {
  position: absolute;
  right: 5px;
  top: 0;
  width: 30px;
  height: 30px;
  line-height: 30px;
  white-space: nowrap;
  z-index: 1003;
  cursor: pointer;
  text-align: center;
  font-size: 14px;
  color: #fff;
}

::v-deep .el-input__inner {
  height: 30px;
  line-height: 30px;
}
</style>
